package com.rr.security.config;

import com.rr.dao.UserDao;
import com.rr.security.AuthTokenManager;
import com.rr.security.filter.AuthFilter;
import com.rr.security.filter.MyLoginAuthenticationFilter;
import com.rr.security.filter.MyLogoutHandler;
import com.rr.service.impl.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @author RR
 * @date 2023/3/14 14:47
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsService myUserDetailsService;
    @Autowired
    private AuthTokenManager authTokenManager;

    /*
    * 章节一：自定义用户名密码验证，实现用户登录
    * 1. 创建配置类，继承WebSecurityConfigurerAdapter类，重写configure方法
    * 2. 自定义实现UserDetailsService接口
    * 3. 将UserDetailsService跟PasswordEncoder配置到以下builder中即可
    * */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder());
        // 取消登录后抹除密码，因为账号对象这里存在内存里面，抹除了之后再次进行登录，
        // 发现账号密码为空，无法跟输入的密码做比较，从而判定为认证失败
        auth.eraseCredentials(false);
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public UserDao userDao(){
        return new UserDao(passwordEncoder());
    }

    @Bean
    public MyUserDetailsService myUserDetailsService(){
        return new MyUserDetailsService(userDao());
    }

    /*
    * 章节二：自定义登录页面
    * 页面资源全放在static下面
    * */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/template/Login.html") // 配置登录页面，需要登录时自动跳转到登录页面
                .loginProcessingUrl("/user/doLogin") // 执行登录操作的url，用于给spring security捕获登录请求
                .defaultSuccessUrl("/template/Success.html") // 登录成功则跳转到指定页面
                .and().authorizeRequests()
                .antMatchers("/", "/user/doLogin","/template/Login.html","/css/*","/picture/*").permitAll() // 这里的请求都不需要登录即可访问
                .antMatchers("/user/adminApi").hasAuthority("admin")
                .antMatchers("/user/roleApi").hasRole("role")
                .anyRequest().authenticated() // 其他请求都需要登录后才能访问
                .and().csrf().disable();  // 取消csrf防护
        // 重定向403页面
        http.exceptionHandling().accessDeniedPage("/template/403.html");
        // 注解页面，配置注销请求，注解成功返回登录页
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/template/Login.html")
                .permitAll();

        // 自定义登录认证过滤器
        MyLoginAuthenticationFilter myLoginAuthenticationFilter = new MyLoginAuthenticationFilter(authenticationManager(), authTokenManager);
        http.addFilterAt(myLoginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class).httpBasic();
        // 自定义授权过滤器
        AuthFilter authFilter = new AuthFilter(authenticationManager(), authTokenManager, userDao());
        http.addFilter(authFilter).httpBasic();
        // 登出过滤器
        MyLogoutHandler myLogoutHandler = new MyLogoutHandler(authTokenManager);
        http.logout().addLogoutHandler(myLogoutHandler);
    }
}
